// pages/community/community.js
const app = getApp()
const db = wx.cloud.database();

Page({
  data: {
    //轮播图
    postersList: [],
    // 列表数据
    contentList: [],
    //加载还是到底
    loading: true,
  },
  onLoad(options) {
    //先拿一次
    this.getAllData()
    this.setData({
      //苹果的tab可以粘滞，安卓不行
      vanTop: app.globalData.vanTop,
      active:1,
    })
  },
  //分页拿数据，虽然叫all，不同栏目下的页index用的是哈希表存
  getAllData(){
    db.collection("administration").get({
      success: (res) => {
        this.setData({
          contentList: res.data[0].contentList,
          postersList: res.data[0].postersList,
        })
        let i = 0
        this._nameMap = new Map()
        this._indexMap = new Map()
        this.data.contentList.map(item => {
          this._nameMap.set(i, item.title)
          this._indexMap.set(i++, 0)
        })
        for (let i = 0; i < this.data.contentList.length; i++) {
          let active = i
          let index = this._indexMap.get(active)
          let name = this._nameMap.get(active)
          this.getContentList(name, index, active)
        }
      }
    })
  },
  // 下拉刷新重新拿数据
  onPullDownRefresh() {
    this.setData({
      loading: true,
      [`contentList${this.data.active}.list`]:""
    })
      this.getAllData()
      wx.stopPullDownRefresh()

  },
  //触底时拿数据
  onReachBottom() {
    this.setData({
      loading: true
    })
    let active = this.data.active
    // if(index){
    let index = this._indexMap.get(active)
    // }
    let name = this._nameMap.get(active)
    
    this.getContentList(name, index, active)
  },
  //拿不同栏目下的数据
  getContentList(name, index, active) {
    db.collection("administration_moreList").where({
      under: name
    }).skip(index * 4).limit(4).get({
      success: (res) => {
        if (res.data.length !== 0) {
          index++
          //不同栏目下的分页拿去页的位置不同
          this._indexMap.set(active, index)
          this.setData({
            [`contentList[${active}].list`]: this.data.contentList[active].list.concat(res.data)
          })


        }
        this.setData({
          loading: false
        })
      }

    })
  },
  // 切换时需要切换active，来识别不同栏目下的下拉
  clickTabs(e) {
    wx.pageScrollTo({
      scrollTop: 0
    })
    if (e.detail.index > -1) {
      this.setData({
        active: e.detail.index
      })
    } else {
      this.setData({
        active: e.currentTarget.dataset.index
      })
    }
  },
  //去详情页面，拿的是id路径
  toDetail(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/administrationDetail/administrationDetail?_id=${item._id}`,
    })
  },
  //分享，朋友圈，收藏
  onShareAppMessage() {},
  onShareTimeline() {},
  onAddToFavorites() {},
})